package com.wencst.generateJPA.builder.web;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import com.wencst.generateJPA.builder.IBuilder;
import com.wencst.generateJPA.config.CoreContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbstractHtmlBuilder implements IBuilder {

	protected CoreContext coreContext;
	public AbstractHtmlBuilder(CoreContext coreContext) {
		this.coreContext = coreContext;
	}
	/**
	 * html模板文件夹路径/templates/freemaker/web
	 */
	@SuppressWarnings("deprecation")
	public void build() {
        Configuration configuration = new Configuration();
        Writer out = null;
        try {
            configuration.setClassForTemplateLoading(AbstractHtmlBuilder.class, "/templates/freemaker/web");
            Template template = configuration.getTemplate(getHtmlName()+".ftl");
            String folder = getDirName();
            File folderFile = new File(folder);
            if (!folderFile.exists()) {
            	folderFile.mkdirs();
            }
            File docFile = new File(folder, getHtmlName()+".html");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            template.process(coreContext.getTb(), out);
        } catch (Exception e) {
        	log.error(e.getMessage(),e);
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
            	log.error(e2.getMessage(),e2);
            }
            try {
                if (null != out) {
                    out.close();
                }
            } catch (Exception e2) {
            	log.error(e2.getMessage(),e2);
            }
        
        }
	}
	/**
	 * 设置当前文件夹路径名称，与java controller中的路径要保持一致
	 */
	public String getDirName() {
		String beanName = coreContext.getTb().getJavaBeanName();
		String folder = coreContext.getWebRealPath() + "/"+beanName+"/";
		return folder;
	}
	/**
	 * 设置html文件名称，增删改查html文件名均不一致，模板名称和生成的html文件名一致
	 * @auth wencst
	 * @date 2018年9月25日
	 * @return
	 */
	public abstract String getHtmlName() ;
}
